from django.shortcuts import render,HttpResponse,redirect,reverse,get_object_or_404
from django.db.models import F,ExpressionWrapper,DecimalField
from cart.models import *
from .models import Cart
from django.contrib.auth.decorators import login_required

from django.contrib import messages



def cart(request):
    carts = Cart.objects.all()
    sort_by = request.POST.get('sort_by')  # 默认按添加时间排序
    print(sort_by)
    if sort_by == 'quantity':
        carts = carts.order_by('quantity')
    elif sort_by == 'name':
        carts = carts.order_by('product__name')
    elif sort_by == 'add_at':
        carts = carts.order_by('add_at')
    elif sort_by == 'price':
        carts = carts.annotate(total_price=F('quantity') * F('product__price')).order_by('-total_price')

    return render(request, 'cart.html', {'carts': carts})


def cart_detail(request, cid):
    products = Cart.objects.get(pk=cid)  # 获取购物车项，并确保属于当前用户
    total_price=products.quantity * products.product.price   #计算总价
    return render(request, 'cart_detail.html', {'products': products,'total_price':total_price} )


def cart_delete(request, cid):
    Cart.objects.get(pk=cid).delete()  # 删除购物车项，并确保属于当前用户
    return redirect(reverse('cart:cart'))

def cart_update(request, cid):
    if request.method == 'POST':
        quantity = request.POST.get('quantity')
        try:
            cart_item = Cart.objects.get(pk=cid)
            if quantity and quantity.isdigit():
                quantity = int(quantity)
                if quantity < 1:
                    messages.error(request, "数量必须至少为1。")
                else:
                    cart_item.quantity = quantity
                    cart_item.save()
                    messages.success(request, "数量更新成功。")
            else:
                messages.error(request, "请输入有效的数量。")
        except ValueError:
            messages.error(request, "数量必须是数字。")
        except Cart.DoesNotExist:
            messages.error(request, "购物车项不存在。")
    return redirect(reverse('cart:cart_detail', args=[cid]))